package org.zfes.snowier.common.monitor.config.ws;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.Optional;

import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.AbstractWebSocketHandler;

import com.google.common.collect.Maps;
import com.google.gson.GsonBuilder;
@Component 
public class MonitorWebSocketHandler extends AbstractWebSocketHandler{
	
	//"signCode_monitor_type_longtime"
	
	 private static final int threadPoolSize=5;
	  //  key : userCode,value ：session
	  public static final Map<String, WebSocketSession> userSocketSessionMap; 
	  
	  static { 
		  
	         userSocketSessionMap = Maps.newConcurrentMap();//new Concur<String, WebSocketSession>(); 
	  } 
	  
	  private ScheduledExecutorService scheduledThreadPool  = Executors.newScheduledThreadPool(threadPoolSize);;
	  
	  @Override 
	  public void afterConnectionEstablished(WebSocketSession session) throws Exception { 
		System.out.println("connect to the websocket success......当前数量:"+ userSocketSessionMap.size());
		
	    String userCode = (String) session.getAttributes().get("userCode");
	    
	    if (userSocketSessionMap.get(userCode) == null) {
	    	
	         userSocketSessionMap.put(userCode, session); 
	    } 
	    //以下业务实现
	    for(int i=0;i<10;i++){ 
	    	
	    	//Thread.currentThread().sleep(1000);
	      //broadcast(new TextMessage(new GsonBuilder().create().toJson("\"number\":\""+i+"\""))); 
	      //session.sendMessage(new TextMessage(new GsonBuilder().create().toJson("\"number\":\""+i+"\""))); 
	   //  sendMessageToUser("lys_AAA" ,new TextMessage(new GsonBuilder().create().toJson("\"number\":\""+i+"\"")));
	    } 
	    
	  }
	  
	  @Override 
	  public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception { 
		  System.out.println("handleMessage: session:" + session.getId() + "||message: "+message.toString());
	    //Message msg=new Gson().fromJson(message.getPayload().toString(),Message.class); 
	    //msg.setDate(new Date()); 
	//   sendMessageToUser(msg.getTo(), new TextMessage(new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create().toJson(msg))); 
	   // session.sendMessage(message); 
	    
	    super.handleMessage(session, message);
	  } 
	  
	  @Override 
	  public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception { 
		  String sessionId=session.getId();
		  System.out.println("handleTransportError: Websocket:" + session.getId() + "TransportError");
		  if (session.isOpen()) {
			  session.close(); 
			  System.out.println("handleTransportError: session excute close ");
	      } 
		  Optional<String>  keyOP= removeFromSessionMap (sessionId);
		  System.out.println("handleTransportError:  Socket会话已经移除:用户ID" +keyOP.orElse(null)); 
		
	  } 
	  
	  @Override 
	  public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception { 
	    System.out.println("afterConnectionClosed: Websocket:" + session.getId() + "已经关闭");
	    Optional<String>  keyOP= removeFromSessionMap (session.getId());
	    System.out.println("afterConnectionClosed: Socket会话已经移除:用户ID" +keyOP.orElse(null)); 
	    System.out.println("afterConnectionClosed: 剩余在线用户: "+userSocketSessionMap.size());
	  } 
	  
	  public void sendMessageToUser(String userCode, TextMessage message) {
		  
		  System.out.println("start sendMessageToUser: userCode:");
		  
		  WebSocketSession session=  userSocketSessionMap.get(userCode);
		  
		  if(session!=null&&session.isOpen()) {
			  try {
				  
			   System.out.println("sendMessageToUser: userCode:" + userCode + "|| message："+message);
				  
				session.sendMessage(message);
				
			} catch (IOException e) {
				e.printStackTrace();
			}
		  }
		  
//	        for (WebSocketSession user : users) {
//	            if (user.getAttributes().get("WEBSOCKET_USERNAME").equals(userName)) {
//	                try {
//	                    if (user.isOpen()) {
//	                        user.sendMessage(message);
//	                    }
//	                } catch (IOException e) {
//	                    e.printStackTrace();
//	                }
//	                break;
//	            }
//	        }
	    }
	  
	  /** 
	   	*      广播
	    */ 
	  public void broadcast(final TextMessage message)  { 
		  
		//  System.out.println("start broadcast: message:"+message);
		  
		  for (Map.Entry<String, WebSocketSession> entry : userSocketSessionMap.entrySet()) {
			  
			  WebSocketSession session=entry.getValue();
			  
			  if (session.isOpen()) {
				  
				  scheduledThreadPool.submit(()->{
					  try {
							session.sendMessage(message);
							
						} catch (IOException e) {
							e.printStackTrace();
						} 
				  });
			  }
		  }
	  } 
	  
	  

	  
	  
	  private Optional<String>  removeFromSessionMap (String sessionId) {
		   Iterator<Entry<String, WebSocketSession>> it = userSocketSessionMap .entrySet().iterator(); 
		    while (it.hasNext()) { 
		      Entry<String, WebSocketSession> entry = it.next(); 
		      if (entry.getValue().getId().equals(sessionId)) { 
		    	  String key =entry.getKey();
		    	  userSocketSessionMap.remove(key);
		    	  return Optional.ofNullable(key);
		      } 
		    } 
		    return Optional.empty();
	  }
	  
	  
//	  /** 
//		       * 给所有在线用户的实时工程检测页面发送消息 
//		 * 
//		 * @param message 
//		 * @throws IOException 
//		 */ 
//		public void sendMessageToJsp(final TextMessage message,String type) throws IOException { 
//		  Iterator<Entry<String, WebSocketSession>> it = userSocketSessionMap.entrySet().iterator(); 
//		
//		  // 多线程群发 
//		  while (it.hasNext()) { 
//		
//		    final Entry<String, WebSocketSession> entry = it.next(); 
//		    if (entry.getValue().isOpen() && entry.getKey().contains(type)) { 
//		      new Thread(new Runnable() { 
//		
//		        public void run() { 
//		          try { 
//		            if (entry.getValue().isOpen()) { 
//		              entry.getValue().sendMessage(message); 
//		            } 
//		            
//		          } catch (IOException  e) { 
//		            e.printStackTrace(); 
//		          } 
//		        } 
//		
//		      }).start(); 
//		    } 
//		
//		  } 
//		}
}
